<script setup>
import { ref, computed, reactive } from 'vue'
import { Icon } from '@iconify/vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { useLayoutThemeStore } from '@/store/layout/layoutTheme.js'
import { useUserStore } from '@/store/business/user.js'
import { useRouter } from 'vue-router'

const { t } = useI18n()
const layoutSetting = useLayoutThemeStore().layoutSetting
const borderRadius = computed(() => layoutSetting.borderRadius)
const userStore = useUserStore()

const formState = ref({
  username: 'admin',
  password: '123456',
  verifyCode: '',
  loginType: 'account',
  agree: true,
  phone: '',
  captcha: '',
})

// 随机验证码 大小写字母 数字
const randomCode = strLen => {
  const code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let str = ''
  for (let i = 0; i < strLen; i++) {
    str += code.charAt(Math.floor(Math.random() * code.length))
  }
  return str
}
const imageCode = ref(randomCode(4))

const iconLoading = ref(false)

const switchLoginType = () => {
  // formState.value.username = ''
  // formState.value.password = ''
  // 验证码重置
  clearInterval(countdownConfig.timerId)
  countdownConfig.isCountingDown = false
  countdownConfig.seconds = 60 // 重置秒数
  formState.value.loginType =
    formState.value.loginType === 'account' ? 'phone' : 'account'
}

const gerCaptcha = () => {
  console.log(1111, '111-验证码')
  startCountdown()
}
// 验证码
const countdownConfig = reactive({
  seconds: 60,
  isCountingDown: false,
  timerId: null,
})
const startCountdown = () => {
  if (!countdownConfig.isCountingDown) {
    countdownConfig.isCountingDown = true
    countdownConfig.timerId = setInterval(() => {
      if (countdownConfig.seconds > 0) {
        countdownConfig.seconds--
      } else {
        clearInterval(countdownConfig.timerId)
        countdownConfig.isCountingDown = false
        countdownConfig.seconds = 60 // 重置秒数
      }
    }, 1000)
  }
}
const router = useRouter()
const onFinish = async values => {
  console.log('Success:', values), (iconLoading.value = true)

  if (
    formState.value.verifyCode.toLocaleLowerCase() !==
    imageCode.value.toLocaleLowerCase()
  ) {
    message.error(t('message.verifyCodeError'))
    imageCode.value = randomCode(4)
    formState.value.verifyCode = ''
    return
  }

  // userStore.login({
  //   username: formState.value.username,
  //   password: formState.value.password,
  //   phone: formState.value.phone,
  //   captcha: formState.value.captcha,
  //   loginType: formState.value.loginType,
  // })
  await router.push('/')
  message.success(t('message.loginSuccess'))

  // 测试动态路由（在这里动态增加路由）
  console.log(1111, '测试动态路由')
}

const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo)
}
</script>

<template>
  <a-form :model="formState" @finish="onFinish" @finishFailed="onFinishFailed">
    <a-form-item
      name="username"
      v-if="formState.loginType === 'account'"
      :rules="[{ required: true, message: t('message.pleaseEnterUsername') }]"
    >
      <a-input
        v-model:value="formState.username"
        :placeholder="t('message.pleaseEnterUsername')"
      >
        <template #prefix>
          <UserOutlined />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      name="phone"
      v-if="formState.loginType === 'phone'"
      :rules="[{ required: true, message: t('message.pleaseEnterPhone') }]"
    >
      <a-input
        v-model:value="formState.phone"
        :placeholder="t('message.pleaseEnterPhone')"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      name="password"
      v-if="formState.loginType === 'account'"
      :rules="[{ required: true, message: t('message.pleaseEnterPassword') }]"
    >
      <a-input-password v-model:value="formState.password">
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item
      name="captcha"
      v-if="formState.loginType === 'phone'"
      :rules="[
        { required: true, message: t('message.pleaseEnterPhoneVerifyCode') },
      ]"
    >
      <a-input v-model:value="formState.captcha">
        <template #suffix>
          <span @click="gerCaptcha" style="cursor: pointer; color: #31bc63">{{
            countdownConfig.seconds != 60
              ? `${countdownConfig.seconds}秒`
              : '获取验证码'
          }}</span>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      name="verifyCode"
      :rules="[{ required: true, message: t('message.pleaseEnterVerifyCode') }]"
    >
      <a-input class="w250px" v-model:value="formState.verifyCode">
        <template #prefix>
          <Icon icon="material-symbols-light:key" />
        </template>
      </a-input>
      <span
        class="ml10px pl10px pr10px font-bold text-22px align-mid cursor-pointer bg-yellow"
        :style="{ borderRadius: `${borderRadius}px` }"
        @click="imageCode = randomCode(4)"
      >
        {{ imageCode }}
      </span>
    </a-form-item>
    <a-form-item :rules="[{ required: true, message: '不能为空' }]">
      <a-checkbox v-model:checked="formState.agree">
        <span style="font-size: 12px">
          我已阅读并同意百分网《<a href="/developer-agreement" class="login-tip"
            >开发者协议条款</a
          >》和《<a href="/privacy-policy" class="login-tip">隐私政策</a>》
        </span>
      </a-checkbox>
    </a-form-item>
    <a-form-item>
      <a-button
        class="w100%"
        type="primary"
        :loading="iconLoading"
        html-type="submit"
      >
        {{ t('setting.login') }}
      </a-button>
    </a-form-item>
    <a-form-item style="text-align: center">
      <div class="login_mode">
        <span @click="switchLoginType" class="login-tip">
          {{ formState.loginType === 'account' ? '验证码登录' : '密码登录' }}
        </span>
        <span type="link" class="login-tip" @click="signIn">开发者注册</span>
      </div>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less">
.login-tip {
  font-size: 12px;
  text-align: center;
  color: #31bc63;
  cursor: pointer;
  font-style: normal;
}
.login_mode {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
